package com.edu.web.servlent;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.edu.entity.User;
import com.edu.service.UserService;
import com.edu.service.impl.UserServiceImpl;

/**
 * Servlet implementation class doLogin
 */
@WebServlet("/doLogin")
public class doLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public doLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("userNum");
        System.out.println(name);
        String pass = request.getParameter("userPass");
        if(!("".equals(name)) && !("".equals(pass))){
            UserService userservices = new UserServiceImpl();
            List<User> list = userservices.queryAll();
            int num = 0;
            for (int i = 0; i < list.size(); i++) {
                User users=list.get(i);
                String a= users.getUserNum();
                String b= users.getUserPass();
                if(name.equals(a)&&pass.equals(b)){
                    Cookie cname = new Cookie("userNum",name);
                    Cookie cpass = new Cookie("userPass",pass);
                    cname.setMaxAge(60);
                    cpass.setMaxAge(60);
                    response.addCookie(cname);
                    response.addCookie(cpass);
                    HttpSession session = request.getSession();
                    session.setAttribute("name", name);
                    session.setAttribute("pass", pass);

                    response.sendRedirect("index.jsp");
                }else{
                    num+=1;
                }
            }
            if(num>=list.size()){
                response.sendRedirect("login.jsp");
            }
        }else{
            response.sendRedirect("login.jsp");
        }
    }

}
